package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.RegexUtils;
import com.kdtech.utils.StringUtils;
import com.kdtech.utils.HtmlCleaner;

/**
 *	6218
 * http://www.eol.cn  中国教育在线
 *
 * @author KK
 *
 */
public class EolNewsAnalyse implements AnalyseNews {

	private static final String[] regex={

		"http://.*[.]eol.cn/.*/[0-9]*/t[0-9]*_[0-9]*[_0-9]*.shtml",
	};

	
	public boolean isDetailPage(String url) {
		return RegexUtils.matchAnyIgnoreCase(url, regex);
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		if (urlMeta.getHtml() == null) {
		}
		NewsMeta news=new NewsMeta();
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();
		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);
		doc.select("div#pagenav,.page_610").remove();
		news.setUrl(url);

		title=doc.select("p.page_title").text();
		if(StringUtils.isBlank(title)){
			title =doc.select("title").text();
			if (title!=null)title=StringUtils.substringBefore(title, "-");
		}
		Elements select=doc.select("#mcontent");
		if(select!=null&&select.size()>0){
			content=select.get(0).ownText();
			if(StringUtils.isBlank(content)){
				select.select("a").remove();
				content=HtmlCleaner.getContentHtml(url,select);
			}
		}
		
		/*
		 * 作者
		 */
		String authorStr=null;
		authorStr=doc.select("p.page_time").text();
		author=StringUtils.substringBetween(authorStr, "作者：","　");

		date=DateUtils.matchDate(url);
		if (date==null){
//			date=DateUtils.matchDate(doc.select("div:containsOwn(发布时间)").text());
		}
		if (StringUtils.isNotBlank(title) && date!=null){
			news.setTitle(StringUtils.trimSpace(title));
			news.setContent(content);
			news.setAuthor(author);
			news.setDate(date);
			news.setType(1);
		}
		return news;
	}
	public static void main(String[] args) {
		String url="http://chuzhong.eol.cn/chu_san_yu_wen_9178/20140506/t20140506_1109412_3.shtml";
		EolNewsAnalyse analyse=new EolNewsAnalyse();
		System.out.println(analyse.isDetailPage(url));
		UrlMeta meta=CrawlHTML.responseToURL(url);
		System.out.println(analyse.parserHtml(meta));
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	
	public boolean isNeedUpdate(){
		return false;
	}
}
